<?php
class step0Action extends sfAction
{
    public function execute($request)
    {
        if ($request->hasParameter('access_token') || $request->hasParameter('code')) {
            // Return from OAuth Dialog, App authorized
            LogInstall::log($request, 'step0_auth');
            $this->redirect(UrlFunctions::genFbUrl('@install_step0?auth=true', true));
        } elseif ($request->getParameter('error') === 'access_denied') {
            // Return from OAuth Dialog, App not authorized
            $this->redirect(UrlFunctions::genFbUrl('@install_step0?auth=false', true));
        } elseif ($request->hasParameter('fb_page_id')) {
            // Return from add.php, the App was just added to a pages
            $url_params = LogInstall::log($request, 'step0_added_page');
            $this->redirect('@install_step1_save?'.http_build_query(array(
                        'page_id' => $request->getParameter('fb_page_id'),
                        'type'    => ($request->getParameter('fb_sig_type') === 'APPLICATION' ? 'app' : 'page'),
                        ), '', '&').'&'.$url_params);
        } elseif ($request->getParameter('auth') === 'false') {
            // Show auth explanation page
            $url_params = LogInstall::log($request, 'step0_auth_denied');
            return 'AccessDenied';
        } elseif ($request->getParameter('auth') === 'true' || $this->isAuthenticated()) {
            // Next step of the install process
            if ($request->getParameter('auth') !== 'true')
                LogInstall::log($request, 'step0'); // First access to step0
                $this->forward('install', 'step1');
                //$this->redirect(UrlFunctions::genFbUrl('@install_step1?access_token='.$this->isAuthenticated(), true));
        } else {
            LogInstall::log($request, 'step0'); // First access to step0
            $url_params = LogInstall::log($request, 'step0_auth_request');
            // Redirect to OAuth Dialog
            return 'AuthRequest';
        }
    }


    /**
     * Specific check on step0 to ensure session refresh
     * TODO: refactoring in FacebookFilter?
     */
    private function isAuthenticated()
    {
        $signed_request = App::getFacebookClient()->getSignedRequest();
        sfContext::getInstance()->getLogger()->debug('{step0Action} '.var_export($signed_request, true));
        return !empty($signed_request['user_id']);
    }
}
?>